<template>
  <view class="edit-profile-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <text class="nav-title">编辑资料</text>
    </view>

    <scroll-view scroll-y class="content-scroll">
      <!-- 头像区域 -->
      <view class="avatar-section">
        <view class="avatar-container" @tap="chooseAvatar">
          <image 
            class="avatar-image" 
            :src="safeAvatarUrl(formData.avatarUrl)" 
            mode="aspectFill"
          />
          <view class="avatar-overlay">
            <text class="camera-icon">📷</text>
            <text class="change-text">更换头像</text>
          </view>
        </view>
      </view>

      <!-- 表单区域 -->
      <view class="form-section">
        <!-- 基本信息 -->
        <view class="form-group">
          <text class="group-title">基本信息</text>
          
          <view class="form-item">
            <text class="label">昵称</text>
            <input 
              class="input" 
              v-model="formData.nickname" 
              placeholder="请输入昵称"
              maxlength="50"
            />
          </view>

          <view class="form-item">
            <text class="label">性别</text>
            <view class="gender-options">
              <view 
                class="gender-option"
                :class="{ active: formData.gender === 0 }"
                @tap="selectGender(0)"
              >
                <text>未知</text>
              </view>
              <view 
                class="gender-option"
                :class="{ active: formData.gender === 1 }"
                @tap="selectGender(1)"
              >
                <text>男</text>
              </view>
              <view 
                class="gender-option"
                :class="{ active: formData.gender === 2 }"
                @tap="selectGender(2)"
              >
                <text>女</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 联系信息 -->
        <view class="form-group">
          <text class="group-title">联系信息</text>
          
          <view class="form-item">
            <text class="label">手机号</text>
            <input 
              class="input" 
              v-model="formData.phone" 
              placeholder="请输入手机号"
              type="number"
              maxlength="11"
            />
          </view>

          <view class="form-item">
            <text class="label">邮箱</text>
            <input 
              class="input" 
              v-model="formData.email" 
              placeholder="请输入邮箱地址"
              type="email"
              maxlength="150"
            />
          </view>
        </view>

        <!-- 账号信息 -->
        <view class="form-group">
          <text class="group-title">账号信息</text>
          
          <view class="form-item">
            <text class="label">用户名</text>
            <input 
              class="input readonly" 
              v-model="formData.username" 
              placeholder="用户名"
              :disabled="true"
            />
            <text class="readonly-tip">用户名不可修改</text>
          </view>

          <view class="form-item">
            <text class="label">登录方式</text>
            <view class="login-type">
              <text class="type-badge" :class="getLoginTypeClass(formData.loginType)">
                {{ getLoginTypeText(formData.loginType) }}
              </text>
            </view>
          </view>

          <view class="form-item">
            <text class="label">角色</text>
            <view class="role-info">
              <text class="role-badge" :class="getRoleClass(formData.role)">
                {{ getRoleText(formData.role) }}
              </text>
            </view>
          </view>
        </view>

        <!-- 家庭信息 -->
        <view class="form-group" v-if="familyInfo">
          <text class="group-title">家庭信息</text>
          
          <view class="form-item">
            <text class="label">所属家庭</text>
            <view class="family-info">
              <text class="family-name">{{ familyInfo.name }}</text>
              <text class="member-count">{{ familyInfo.memberCount || 0 }}名成员</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <button class="save-btn" @tap="saveProfile" :loading="saving">
        {{ saving ? '保存中...' : '保存修改' }}
      </button>
      <button class="password-btn" @tap="changePassword">
        修改密码
      </button>
    </view>

    <!-- 修改密码弹窗 -->
    <view class="password-modal" v-if="showPasswordModal" @tap="closePasswordModal">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">修改密码</text>
          <text class="close-btn" @tap="closePasswordModal">×</text>
        </view>
        
        <view class="modal-body">
          <view class="form-item">
            <text class="label">原密码</text>
            <input 
              class="input" 
              v-model="passwordForm.oldPassword" 
              placeholder="请输入原密码"
              password
            />
          </view>
          
          <view class="form-item">
            <text class="label">新密码</text>
            <input 
              class="input" 
              v-model="passwordForm.newPassword" 
              placeholder="请输入新密码"
              password
            />
          </view>
          
          <view class="form-item">
            <text class="label">确认密码</text>
            <input 
              class="input" 
              v-model="passwordForm.confirmPassword" 
              placeholder="请再次输入新密码"
              password
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @tap="closePasswordModal">取消</button>
          <button class="confirm-btn" @tap="submitPasswordChange" :loading="changingPassword">
            {{ changingPassword ? '修改中...' : '确认修改' }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { api, uploadFile } from '@/utils/request'
import imageHelper from '@/utils/imageHelper'
import config from '@/utils/config.js'

export default {
  name: 'EditProfile',
  
  data() {
    return {
      formData: {
        nickname: '',
        avatarUrl: '',
        gender: 0,
        phone: '',
        email: '',
        username: '',
        loginType: '',
        role: ''
      },
      familyInfo: null,
      saving: false,
      // 修改密码相关
      showPasswordModal: false,
      changingPassword: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    }
  },

  computed: {
    ...mapState('user', ['userInfo'])
  },

  onLoad() {
    this.initFormData()
    this.loadFamilyInfo()
  },

  methods: {
    ...mapActions('user', ['updateUserInfo']),

    // 初始化表单数据
    initFormData() {
      if (this.userInfo) {
        this.formData = {
          nickname: this.userInfo.nickname || '',
          avatarUrl: this.userInfo.avatarUrl || '',
          gender: this.userInfo.gender || 0,
          phone: this.userInfo.phone || '',
          email: this.userInfo.email || '',
          username: this.userInfo.username || '',
          loginType: this.userInfo.loginType || '',
          role: this.userInfo.role || ''
        }
      }
    },

    // 加载家庭信息
    async loadFamilyInfo() {
      if (this.userInfo && this.userInfo.familyId) {
        try {
          // 修正API调用，确保请求正确的URL
          const response = await api.get(`/user/my-family`)
          if (response.code === 200) {
            this.familyInfo = response.data
          } else {
            console.warn('加载家庭信息失败:', response.message);
          }
        } catch (error) {
          console.error('加载家庭信息时发生异常:', error)
        }
      }
    },

    // 安全的头像URL
    safeAvatarUrl(url) {
      if (!url) {
        return imageHelper.getDefaultAvatar()
      }
      return imageHelper.safeImageUrl(url, 'avatar')
    },

    // 选择头像
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.uploadAvatar(res.tempFilePaths[0])
        }
      })
    },

    // 上传头像
    async uploadAvatar(filePath) {
      try {
        uni.showLoading({ title: '上传中...' })
        
        const response = await uploadFile({
          // 使用正确的统一上传接口
          url: '/file/upload', 
          filePath: filePath,
          name: 'file'
        })

        if (response.code === 200) {
          // 后端返回的是相对路径，例如 /uploads/uuid.jpg
          this.formData.avatarUrl = response.data
          uni.showToast({
            title: '头像上传成功',
            icon: 'success'
          })
        } else {
          throw new Error(response.message || '上传失败')
        }
      } catch (error) {
        console.error('上传头像失败:', error)
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 选择性别
    selectGender(gender) {
      this.formData.gender = gender
    },

    // 获取登录方式文本
    getLoginTypeText(type) {
      const typeMap = {
        'wechat': '微信登录',
        'account': '账号密码',
        'phone': '手机号登录'
      }
      return typeMap[type] || '未知'
    },

    // 获取登录方式样式
    getLoginTypeClass(type) {
      return {
        'wechat': 'type-wechat',
        'account': 'type-account',
        'phone': 'type-phone'
      }[type] || 'type-default'
    },

    // 获取角色文本
    getRoleText(role) {
      const roleMap = {
        'admin': '管理员',
        'member': '普通成员'
      }
      return roleMap[role] || '未知'
    },

    // 获取角色样式
    getRoleClass(role) {
      return {
        'admin': 'role-admin',
        'member': 'role-member'
      }[role] || 'role-default'
    },

    // 保存资料
    async saveProfile() {
      if (!this.validateForm()) {
        return
      }

      this.saving = true
      try {
        const updateData = {
          nickname: this.formData.nickname,
          avatarUrl: this.formData.avatarUrl,
          gender: this.formData.gender,
          phone: this.formData.phone,
          email: this.formData.email
        }

        await this.updateUserInfo(updateData)
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })

        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error('保存失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      } finally {
        this.saving = false
      }
    },

    // 表单验证
    validateForm() {
      if (!this.formData.nickname.trim()) {
        uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        })
        return false
      }

      if (this.formData.email && !this.validateEmail(this.formData.email)) {
        uni.showToast({
          title: '邮箱格式不正确',
          icon: 'none'
        })
        return false
      }

      if (this.formData.phone && !this.validatePhone(this.formData.phone)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        })
        return false
      }

      return true
    },

    // 验证邮箱
    validateEmail(email) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      return emailRegex.test(email)
    },

    // 验证手机号
    validatePhone(phone) {
      const phoneRegex = /^1[3-9]\d{9}$/
      return phoneRegex.test(phone)
    },

    // 修改密码
    changePassword() {
      if (this.formData.loginType !== 'account') {
        uni.showToast({
          title: '当前登录方式不支持修改密码',
          icon: 'none'
        })
        return
      }
      this.showPasswordModal = true
    },

    // 关闭密码弹窗
    closePasswordModal() {
      this.showPasswordModal = false
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    },

    // 提交密码修改
    async submitPasswordChange() {
      if (!this.validatePasswordForm()) {
        return
      }

      this.changingPassword = true
      try {
        const response = await api.post('/user/change-password', {
          oldPassword: this.passwordForm.oldPassword,
          newPassword: this.passwordForm.newPassword
        })

        if (response.code === 200) {
          uni.showToast({
            title: '密码修改成功',
            icon: 'success'
          })
          this.closePasswordModal()
        } else {
          throw new Error(response.message || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        uni.showToast({
          title: error.message || '密码修改失败',
          icon: 'none'
        })
      } finally {
        this.changingPassword = false
      }
    },

    // 验证密码表单
    validatePasswordForm() {
      if (!this.passwordForm.oldPassword) {
        uni.showToast({
          title: '请输入原密码',
          icon: 'none'
        })
        return false
      }

      if (!this.passwordForm.newPassword) {
        uni.showToast({
          title: '请输入新密码',
          icon: 'none'
        })
        return false
      }

      if (this.passwordForm.newPassword.length < 6) {
        uni.showToast({
          title: '新密码至少6位',
          icon: 'none'
        })
        return false
      }

      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        })
        return false
      }

      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-profile-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.nav-header {
  background: white;
  padding: 40rpx;
  text-align: center;
  border-bottom: 1rpx solid #eee;
  
  .nav-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.content-scroll {
  flex: 1;
  padding-bottom: 200rpx;
}

.avatar-section {
  background: white;
  padding: 60rpx 40rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: center;
  
  .avatar-container {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    border-radius: 50%;
    overflow: hidden;
    
    .avatar-image {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background: #f0f0f0;
    }
    
    .avatar-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.4);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s;
      
      .camera-icon {
        font-size: 48rpx;
        color: white;
        margin-bottom: 8rpx;
      }
      
      .change-text {
        font-size: 24rpx;
        color: white;
      }
    }
    
    &:active .avatar-overlay {
      opacity: 1;
    }
  }
}

.form-section {
  .form-group {
    background: white;
    margin-bottom: 20rpx;
    padding: 40rpx;
    
    .group-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 32rpx;
      display: block;
    }
    
    .form-item {
      display: flex;
      align-items: center;
      margin-bottom: 32rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .label {
        width: 140rpx;
        font-size: 28rpx;
        color: #333;
        flex-shrink: 0;
      }
      
      .input {
        flex: 1;
        padding: 20rpx 24rpx;
        border: 1rpx solid #e0e0e0;
        border-radius: 8rpx;
        font-size: 28rpx;
        background: #fafafa;
        
        &.readonly {
          background: #f0f0f0;
          color: #999;
        }
      }
      
      .readonly-tip {
        font-size: 24rpx;
        color: #999;
        margin-left: 16rpx;
      }
    }
  }
}

.gender-options {
  display: flex;
  gap: 16rpx;
  flex: 1;
  
  .gender-option {
    flex: 1;
    padding: 16rpx;
    text-align: center;
    border: 1rpx solid #e0e0e0;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #666;
    background: #fafafa;
    
    &.active {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-color: transparent;
    }
  }
}

.login-type, .role-info, .family-info {
  flex: 1;
  display: flex;
  align-items: center;
}

.type-badge, .role-badge {
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  font-size: 24rpx;
  color: white;
  
  &.type-wechat {
    background: #1aad19;
  }
  
  &.type-account {
    background: #007AFF;
  }
  
  &.type-phone {
    background: #FF9500;
  }
  
  &.role-admin {
    background: #FF3B30;
  }
  
  &.role-member {
    background: #34C759;
  }
  
  &.type-default, &.role-default {
    background: #999;
  }
}

.family-name {
  font-size: 28rpx;
  color: #333;
  margin-right: 16rpx;
}

.member-count {
  font-size: 24rpx;
  color: #999;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 24rpx 40rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #eee;
  display: flex;
  gap: 24rpx;
  
  .save-btn, .password-btn {
    flex: 1;
    padding: 24rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    border: none;
  }
  
  .save-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
  }
  
  .password-btn {
    background: #f5f5f5;
    color: #666;
  }
}

// 修改密码弹窗样式
.password-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  
  .modal-content {
    background: white;
    border-radius: 24rpx;
    width: 90%;
    max-width: 600rpx;
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 40rpx;
      border-bottom: 1rpx solid #f0f0f0;
      
      .modal-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close-btn {
        font-size: 48rpx;
        color: #999;
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    
    .modal-body {
      padding: 40rpx;
      
      .form-item {
        margin-bottom: 32rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          display: block;
          font-size: 28rpx;
          color: #333;
          margin-bottom: 12rpx;
        }
        
        .input {
          width: 100%;
          padding: 24rpx;
          border: 1rpx solid #e0e0e0;
          border-radius: 12rpx;
          font-size: 28rpx;
          background: #fafafa;
          box-sizing: border-box;
        }
      }
    }
    
    .modal-footer {
      display: flex;
      gap: 24rpx;
      padding: 20rpx 40rpx 40rpx;
      
      .cancel-btn, .confirm-btn {
        flex: 1;
        padding: 24rpx;
        border-radius: 12rpx;
        font-size: 28rpx;
        border: none;
      }
      
      .cancel-btn {
        background-color: #f5f5f5;
        color: #666;
      }
      
      .confirm-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
      }
    }
  }
}
</style> 